package com.yoyo.itravel.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description JSON操作工具类
 * @Author HZX
 * @Version 1.0
 * @Date 2020/6/19 11:28
 */
public class JSONUtils {

	/* 私有化构造器 */
	private JSONUtils() {};

	/**
	 * @Description 直接将传入的对象序列化为json，并且写回客户端
	 *
	 * @Param obj
	 * @Param response
	 * @Return void
	 */
	public static void writeValueToResponse(Object obj, HttpServletResponse response) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		response.setContentType("application/json;charset=utf-8");
		mapper.writeValue(response.getOutputStream(), obj);
	}

	/**
	 * @Description 传入的对象序列化为json字符串，并返回
	 *
	 * @Param obj
	 * @Return java.lang.String
	 */
	public static String writeValueAsString(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(obj);
	}


}
